import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { ConfigService } from './config.service';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class Code2NameService {
  private _map: any = {};
  private cache = false;
  constructor(private http: Http, private config: ConfigService) {
  }
  public getCountyName(id: string): Observable<any> {
    const key = 'countyID_' + id;
    if (this._map[key] && this.cache) {
      return Observable.fromPromise(Promise.resolve(this._map[key]));
    }
    let url, options;
    url = this.config.get('url') + '?service=CountyInfoService&method=getCountyByID';
    options = { countyId: id };
    return this.http.post(url, options).map((res: Response) => {
      const body = res.json();
      if (this.cache) {
        this._map[key] = body.info.countyName;
      }
      return body.info.countyName;
    });
  }
}
